package br.edu.ufabc.lnc.peanho.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;

import java.awt.image.BufferedImage;

public class Sprite {

	private final String id;
	private BufferedImage image;
	private final Rectangle boundingBox;
	private final int[] readings;
	private static Font font = new Font("Sans", Font.BOLD, 12);

	public Sprite(String id, int[] readings, BufferedImage image, int x, int y) {
		this.id = id;
		this.readings = readings;
		this.image = image;
		this.boundingBox = new Rectangle(x, y, image.getWidth(), image
				.getHeight());
	}

	public String getId() {
		return id;
	}

	public void updatePosition(double x, double y) {
		double xPos = x - image.getWidth() / 2;
		double yPos = y - image.getHeight() / 2;
		boundingBox.setRect(xPos, yPos, image.getWidth(), image.getHeight());
	}

	/**
	 * Desenha a imagem deste sprite no {@code buffer}.
	 * 
	 * @param buffer
	 *            {@link BufferedImage} no qual a imagem deste sprite será
	 *            desenhada
	 */
	public void drawSprite(BufferedImage buffer) {
		Graphics2D g2d = buffer.createGraphics();
		g2d.drawImage(image, boundingBox.x, boundingBox.y, null);
		FontMetrics fm = g2d.getFontMetrics();
		int x = (int) (boundingBox.getCenterX() - fm.stringWidth(id) / 2);
		int y = (int) (boundingBox.getMaxY() + fm.getHeight());
		g2d.setColor(Color.BLACK);
		g2d.setFont(font);
		g2d.drawString(id, x, y);
		y += fm.getHeight();
		String header = "(" + readings[0] + ", " + readings[1] + ", "
				+ readings[2] + ")";
		g2d.drawString(header, x, y);
		g2d.dispose();
	}

	/**
	 * Retorna {@code true} caso o ponto de coordenadas {@code x}, {@code y}
	 * esteja contido no retangulo que delimita a imagem desta sprite.
	 * 
	 * @param x
	 *            coordenada x do ponto
	 * @param y
	 *            coordenada y do ponto
	 * @return {@code true} caso contenha o ponto, {@code false} do contrário
	 */
	public boolean contains(int x, int y) {
		return boundingBox.contains(x, y);
	}

	public int[] getReadings() {
		return readings;
	}

	public void setReadings(int[] readings) {
		int i = 0;
		for (int reading : readings) {
			readings[i] = reading;
		}

	}

	public Point getPosition() {
		int x = (int) boundingBox.getX();
		int y = (int) boundingBox.getY();
		return new Point(x, y);

	}

}
